//
//  TDTabBar.swift
//  微博
//
//  Created by tong dan on 16/2/29.
//  Copyright © 2016年 tong dan. All rights reserved.
//

import UIKit

class TDTabBar: UITabBar {

    
    //10.撰写按钮点击事件要执行的闭包(定义闭包)
    var composeButtonClickClourse:(() ->())?
    
    //4.把composeButton添加上去
    override init(frame: CGRect) {
        super.init(frame: frame)
        //把composeButton添加上去
        addSubview(composeButton)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
   //5.调整子控件位置
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //子控件的center尽量不要使用父控件的 center去计算，因为参照物不一样
        composeButton.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5)
        
    //7.设置子控件位置，让其平分
        let childW: CGFloat = self.frame.width * 0.2
        
        //定义一个索引，用来记录当前遍历到了第几个按钮
        var index = 0
        //遍历查询到指定的button
        for childView in self.subviews{
        
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!){
                
                //设置宽度和位置
                childView.frame.size.width = childW
                childView.frame.origin.x = CGFloat(index) * childW
                
                index++
            
                // 如果发现将要遍历  `发现` 按钮的时候,就让 index++(空一个位置)
                if index == 2 {
                
                    index++
                
                }
            }
        
        }
        
    }
 
    
    
   //3.懒加载(private修饰按钮外界拿不到)
    private lazy var composeButton: UIButton = {
    
        let button = UIButton()
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //6.设置➕图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)

        //内容多大就设置控件多大
        button.sizeToFit()
        
        //8.添加➕的点击事件
        button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
    return button
    }()
    
    //9.把事件抛给控制器（执行闭包）
    @objc private func composeButtonClick(){
    
    composeButtonClickClourse?()
    
    }
}
